<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    const UNACTIVED_USER_FLAG = 0;
    const BANNED_USER_FLAG = 2;
    
    const ERROR_UNACTIVED_USER = 3;
    const ERROR_BANNED_USER = 4;
    var $user_id;
    var $name;
    var $user_name;
    /**
     * Authenticates a user.
     * 
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
    	// save session
        $user = User::model()->find('user_name=:user_name', array(':user_name' => $this->username));

        if (!$user)
        {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        }
        else if ($user->password != md5($this->password))
        {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        }
        else if($user->active == self::UNACTIVED_USER_FLAG)
        {
            // User chưa active
            $this->errorCode = self::ERROR_UNACTIVED_USER;
        }
        else if($user->active == self::BANNED_USER_FLAG)
        {
            // User bị banned
            $this->errorCode = self::ERROR_BANNED_USER;
        }
        else
        {
            $this->errorCode = self::ERROR_NONE;
            $this->user_id = $user->user_id;
            $this->name = $user->your_name;
            $this->user_name = $user->user_name;
            $this->setState('liberty_acc_from', $user->lr_acc);
            
            // update last_login and last login ip address
            $user->last_login = date('Y-m-d H:i:s');
            $user->last_ip = Yii::app()->request->userHostAddress;
            $user->save();
            
            // save session
            Yii::app()->session->open();
            Yii::app()->session['isLogin'] = true;
            Yii::app()->session['user_id'] = $user->user_id;
        }
        return!$this->errorCode;
    }
    public function getId()
    {
        return $this->user_id;
    }

    public function getName()
    {
        return $this->user_name;
    }
    
}